package com.tally.server.service;

import com.tally.server.domain.Exp;
import com.tally.server.domain.ExpExample;
import com.tally.server.dto.ExpDTO;
import com.tally.server.dto.PageDTO;
import com.tally.server.mapper.ExpMapper;
import com.tally.server.utils.CopyUtil;
import com.tally.server.utils.UUIDUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Date;

@Service
public class ExpService {

    @Autowired
    private ExpMapper expMapper;

    /**
     * 列表查询
     */
    public void list(PageDTO pageDTO) {
        PageHelper.startPage(pageDTO.getPage(), pageDTO.getSize());
        ExpExample expExample = new ExpExample();
        List<Exp> expList = expMapper.selectByExample(expExample);
        PageInfo<Exp> pageInfo = new PageInfo<>(expList);
        pageDTO.setTotal(pageInfo.getTotal());
        List<ExpDTO> expDTOList = CopyUtil.copyList(expList, ExpDTO.class);
        pageDTO.setList(expDTOList);
    }

    /**
     * 保存，id有值时更新，无值时新增
     */
    public void save(ExpDTO expDTO) {
        Exp exp = CopyUtil.copy(expDTO, Exp.class);
        ExpExample expExample = new ExpExample();
        expExample.createCriteria().andUserIdEqualTo(exp.getUserId());
        if(expMapper.countByExample(expExample) > 0){
            update(exp);
        }else{
            insert(exp);
        }
    }

    /**
     * 新增
     */
    private void insert(Exp exp) {
        Date now = new Date();
        exp.setCreateTime(now);
        exp.setUpdateTime(now);
        expMapper.insert(exp);
    }

    /**
     * 更新
     */
    private void update(Exp exp) {
        exp.setUpdateTime(new Date());
        expMapper.updateByPrimaryKey(exp);
    }

    public ExpDTO selectByUserId(Integer userId) {
        Exp exp = expMapper.selectByPrimaryKey(userId);
        return CopyUtil.copy(exp,ExpDTO.class);
    }

    public void addExp(Integer userId,Integer expValue){
        if(expValue == 0){
            return;
        }
        Exp expDb = expMapper.selectByPrimaryKey(userId);
        if(expDb == null){
            Exp exp = new Exp();
            exp.setUserId(userId);
            exp.setExp(expValue);
            insert(exp);
        }else{
            expDb.setExp(expDb.getExp() + expValue);
            update(expDb);
        }
    }
}
